package com.xbwang.controller;

import com.xbwang.service.WeChatService;
import com.xbwang.utils.SignUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 微信公众号controller
 * @author xbwang
 * @date 2023/9/20 14:03
 **/
@Api(tags = "微信公众号controller")
@Controller
@RequestMapping("/weChat")
public class WechatController {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Value("${wxToken}")
    private String wxToken;
    @Value("${DNS_URl}")
    private String dns_url;
    @Value("${appId}")
    private String appId;
    @Value("${appsecret}")
    private String appsecret;
    @Resource
    private WeChatService weChatService;
    @Resource
    private RestTemplate restTemplate;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 微信公众号接入
     *
     * @param request
     * @param response
     */
    @ApiOperation("微信公众号接入")
    @GetMapping("/access")
    public void wxlogin(HttpServletRequest request, HttpServletResponse response) {
        String signature = request.getParameter("signature");
        String timestamp = request.getParameter("timestamp");
        String nonce = request.getParameter("nonce");
        String echostr = request.getParameter("echostr");
        PrintWriter out = null;
        try {
            out = response.getWriter();
        } catch (IOException e) {
            logger.error("获取PrintWriter异常");
        }
        if (SignUtil.checkSignature(wxToken,signature, timestamp, nonce)) {
            logger.info("微信公众号接入成功！");
            out.print(echostr);
        }
        out.close();
    }

    /**
     * 消息被动回复
     *
     * @param request
     * @param response
     */
    @ApiOperation("消息被动回复")
    @PostMapping("/access")
    public void feedbackMsg(HttpServletRequest request, HttpServletResponse response) {
        //响应消息
        PrintWriter out = null;
        try {
            response.setCharacterEncoding("utf-8");
            out = response.getWriter();
            //被动回复消息
            String feedmsg = null;
            feedmsg = weChatService.feedbackMsg(request, response);
            logger.info("被动回复消息：{}", feedmsg);
            out.print(feedmsg);
        } catch (IOException e) {
            logger.error("获取PrintWriter异常", e);
        }
        out.close();
    }

//    /**
//     * 菜单栏页面跳转
//     *
//     * @param request
//     * @param response
//     * @return
//     */
//    @RequestMapping("/homePage")
//    public Object wx2alarm(HttpServletRequest request, HttpServletResponse response, String code) {
//        String openid = null;
//        String userAgent = request.getHeader("user-agent").toLowerCase();
//        if (userAgent != null) {
//            if (userAgent.contains("android") || userAgent.contains("iphone") || userAgent.contains("wechat")) {
//                //手机端或者微信客户端
//                System.out.println(code);
//                //获取微信id
//                String requestUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+appId+"&secret=" +appsecret+
//                        "&code=" + code + "&grant_type=authorization_code";
////                ResponseEntity<WxToken> entity = restTemplate.getForEntity(requestUrl, WxToken.class);
//                String conent = restTemplate.getForObject(requestUrl, String.class);
////                WxToken token = entity.getBody();
////                openid = token.getOpenid();
//                System.out.println(openid);
//                logger.info("openid={}",openid);
//            }
//        }
//        return "redirect:" + dns_url + "/screen/html/index.html?openid=" + openid;
//    }
    @ApiOperation("测试接口")
    @ResponseBody
    @PostMapping("/test")
    public String test(){
        stringRedisTemplate.opsForSet().add("test","微信公众号测试");
        return "success";
    }
}
